package cn.wolfcode.crm.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController {
    // Spring 容器中存在 ServletContext 对象,直接定义 ServletContext 类型的字段使用,贴注解
    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/upload")
    public ModelAndView upload(@ModelAttribute("img") Part pic) throws IOException {
        ModelAndView mv = new ModelAndView();
        System.out.println(pic.getContentType());
        System.out.println(pic.getName());
        System.out.println(pic.getSize());
        System.out.println(servletContext.getRealPath("/static/Img"));

        // 获取图片存放的根路径
        String realPath = servletContext.getRealPath("/static/Img");
        System.out.println("根路径"+realPath);
        // 获取文件名
        String picHeader = pic.getHeader("Content-Disposition");
        String fileName = picHeader.substring(picHeader.lastIndexOf("."),picHeader.length()-1);
        System.out.println("切割后的文件名:"+fileName);

        // 随机文件名+拓展名
        String newFileName = UUID.randomUUID().toString() + fileName;
        System.out.println("新文件名:"+newFileName);
        // 写到 static 目录下的 Img 文件夹中*/
        pic.write(realPath+"/"+newFileName);
        mv.addObject("img","/static/Img/"+newFileName);
        mv.setViewName("hello");
        return mv;
    }

}
